package com.cjjd.c.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import com.cjjd.c.R;

/**
 * ----------------------------------
 * Created by xyd on 2017/8/9.
 * <p/>
 * 描  述：
 * 1. 带下划线的editTextview
 * 2. 点击 drawableRight 清除内容
 * <p/>
 * 修订历史:
 * ----------------------------------
 */


public class MyEditText extends EditText {


    private Paint mPaint;
    private float line_height = 1.0f;
    private int line_color;

    public MyEditText(Context context) {
        this(context, null);
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyEditText);
        line_height = ta.getDimension(R.styleable.MyEditText_line_height, 1.5f);
        line_color = ta.getColor(R.styleable.MyEditText_line_color, 0x000000);
        ta.recycle();

        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(line_height);
        // 你可以根据自己的具体需要在此处对画笔做更多个性化设置
        mPaint.setColor(line_color);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        final int DRAWABLE_LEFT = 0;
        final int DRAWABLE_TOP = 1;
        final int DRAWABLE_RIGHT = 2;
        final int DRAWABLE_BOTTOM = 3;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (getCompoundDrawables() != null &&
                        getCompoundDrawables()[DRAWABLE_RIGHT] != null &&
                        event.getRawX() >= (getRight() - getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width()) - getCompoundDrawablePadding()) {
                    //Log.e("xyd", "right button clicked");
                    setText("");
                    return true;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void setOnTouchListener(OnTouchListener l) {
        super.setOnTouchListener(l);
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 画底线
        canvas.drawLine(
                0,
                this.getHeight() - line_height,
                this.getWidth(),
                this.getHeight() - line_height,
                mPaint);


    }
}
